/**
 * Copyright 2016-2018 mobaas.com
 */
package com.mobaas.devops.schedule.job;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.client.RestClientException;

import com.mobaas.devops.ComponentFactory;
import com.mobaas.devops.HealthChecker;
import com.mobaas.devops.HttpHealthResult;
import com.mobaas.devops.model.WebUrl;
import com.mobaas.devops.model.WebUrlLog;
import com.mobaas.devops.service.WebUrlService;

/**
 * 
 * @author billy zhang
 * 
 */
public class WebUrlScanJob extends AbstractJob {

    private static final Logger logger = LoggerFactory.getLogger(WebUrlScanJob.class);
    
    @Autowired
    private WebUrlService weburlService;
    
    @Autowired
    private ComponentFactory<HealthChecker> checkerFactory;
    
    private int connectTimeout;
    
    private int readTimeout;
    
    @Override
	protected void doExecute(Map<String, Object> jobData) {
    	
    		connectTimeout = (Integer)jobData.get("connectTimeout");
    		readTimeout = (Integer)jobData.get("readTimeout");
    		
		List<WebUrl> list = weburlService.selectWebUrlList(1);
		
		for (WebUrl url : list) {
			scanUrl(url);
		}
	}
	
	private void scanUrl(WebUrl url) {
		
		Map<String, Object> data = new HashMap<>();
		data.put("connectTimeout", connectTimeout);
		data.put("readTimeout", readTimeout);
		data.put("url", url.getUrl());
		
		WebUrlLog log = new WebUrlLog();
		log.setUrlId(url.getId());
		log.setScanTime(new Date());
    		logger.info("扫描：" + url.getUrl());
		long start = new Date().getTime();
		try {
			HttpHealthResult result = checkerFactory.getComponent("http").check(data);
			
			log.setDuration((int)(new Date().getTime() - start));
			log.setScanStatus(result.getHttpStatus());
		} catch (RestClientException ex) {
			log.setDuration((int)(new Date().getTime() - start));
			log.setScanStatus(599);
		}
		
		weburlService.insertWebUrlLog(log);
	}
}
